package com.newcapec.news.servlet;

import com.newcapec.news.dao.SysUserDao;
import com.newcapec.news.dao.impl.SysUserDaoImpl;
import com.newcapec.news.entity.SysUser;
import com.newcapec.news.util.MD5Util;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Objects;

/**
 * @Description: 登录Servelt
 * @Author: fujun
 * @Date : 2022/3/16 15:53
 * @Version : 1.0
 * @company 新开普电子股份有限公司
 */
public class LoginServlet extends HttpServlet {


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //规范字符集
//        req.setCharacterEncoding("utf-8");
//        resp.setCharacterEncoding("utf-8");

        //获取用户输入的验证码
        String  code=req.getParameter("code");

        //获取程序中生成的验证码

        String validateCode= (String) req.getSession().getAttribute("validateCode");

        System.out.println(code);
        System.out.println(validateCode);

        //和程序中生成的验证码进行比较

        if(!Objects.equals(code,validateCode)){
            //验证码错误
            resp.sendRedirect("login.h?type=4");
            return;
        }


        //获取用户传递的参数

        String acct=req.getParameter("userAcct");
        String pwd=req.getParameter("userPwd");
        SysUserDao sysUserDao=new SysUserDaoImpl();
        if(acct!=null && pwd!=null){
          SysUser user= sysUserDao.getUserByAcct(acct);
          if(user==null){
              //用户名不存在
                resp.sendRedirect("login.h?type=1");
          }else{
              if(Objects.equals(MD5Util.toMD5(pwd),user.getPwd())){
                    //用户登录成功  -页面跳转
                  //登录成功，我们将用户信息保存到session对象
                 HttpSession session= req.getSession();
                 session.setAttribute("user",user);

                resp.sendRedirect("index.h");
              }else{
                  //密码错误
                  resp.sendRedirect("login.h?type=2");
              }
          }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
